import React, { useRef, useState, useEffect } from 'react';
import ATable, { ATableColumn, SearchToolBarProps } from '@apulis/table';
import type { ActionType } from '@apulis/table/lib/typing';
import { apwsfRequest,  } from '@/utils/request';
import { imageAPI, imageVersionAPI, getImageVersions } from '../service';
import { Tabs, Button, Modal, Card, Select, Space, Input } from 'antd'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'
import trans from '@/utils/translate';
import format from '@/utils/format';
import { aphfRequest } from '@/utils/request';
import { model } from './SelectModel';
import { bytesToSize } from '@/utils/utils';

const { TabPane } = Tabs;
const { Option } = Select;

interface Props {
  setTabImage: any;
  models: model[];
  publicImages: any[];
  imageSelect: imageS;
  setImageSelect: any;
  tabImage: string;
}
interface imageVersion {
  imageVersion: string,
  imageSize: string,
  updateAt: string,
}
interface image {
  id: string,
  imageName: string;
  versionCount: string;
  createAt: string;
};
interface imageS {
  containerImage: string;
  containerImageTag: string;
}
const SelectImage: React.FC<Props> = (props) => {
  const {
    models,
    publicImages,
    setImageSelect,
    imageSelect,
    setTabImage,
    tabImage,
  } = props;
  // const imageArr = models[0]?.engine ? models[0].engine.split(':') : [];

  // imageArrimageArr.forEach();
  // const publicVersion = imageArr[imageArr]
  const [expandedKeysImage, setExpandedKeysImage] = useState<React.Key[]>(['']);
  const [imageKeys, setImageKeys] = useState<React.Key[]>([]);
  const imageVersionRef = useRef<ActionType>();
  const [imageId, setImageId] = useState(-1);
  const [modal, setModal] = useState(false); // 控制镜像选择弹窗
  const [imageVersions, setImageVersions] = useState<string[]>([]);
  const [publicSelect, setPublicSelect] = useState('');
  const [publicName, setPublicName] = useState('');
  const [publicVersion, setPublicVersion] = useState('');
  // const [public]
  const columnsImage: ATableColumn<image>[] = [
    {
      title: trans('deployOnline.edgeInference.add.imageName'),
      dataIndex: 'imageName',
    },
    {
      title: trans('deployOnline.edgeInference.add.versionCount'),
      dataIndex: 'versionCount',
    },
    {
      title: trans('deployOnline.edgeInference.add.createAt'),
      dataIndex: 'createAt',
      format: 'time'
    },
  ];
  const columnsImageVersion: ATableColumn<imageVersion>[] = [
    {
      title: trans('deployOnline.edgeInference.add.imageVersion'),
      dataIndex: 'imageVersion',
    },
    {
      title: trans('deployOnline.edgeInference.add.imageSize'),
      dataIndex: 'imageSize',
      render: (text: string) => bytesToSize(text),
    },
    {
      title: trans('deployOnline.edgeInference.add.updateAt'),
      dataIndex: 'updateAt',
      format: 'time'
    },
  ];
  const expandImageChange = (rows: Readonly<React.Key[]>) => {
    const arrTemp: React.Key[] = ['']
    setExpandedKeysImage(arrTemp.concat(rows[rows.length - 1]))
    setImageKeys([]);
  }
  const selectImage = () => {
    getImageVersions(imageId).then(res => {
      if (res && res.code === 0) {
        const { items } = res.data as { items: imageVersion[]};
        const versions = items.map(v => v.imageVersion);
        console.log(versions);
        setImageVersions(versions);
        setModal(false);
      }
    })
  }

  const searchList: SearchToolBarProps[] = [
    {
      type: 'input',
      name: 'searchName',
      label: '镜像名称',
      placeholder: '请输入镜像名称',
      inputProps: { allowClear: true },
    }
  ]
  useEffect(() => {
    setImageSelect({
      containerImage: publicName,
      containerImageTag: publicVersion,
    });
  }, [publicName])
  useEffect(() => {
    // 公有镜像是默认，我的镜像由用户选择
    if (tabImage === 'public') {
      setImageSelect({
        containerImage: publicName,
        containerImageTag: publicVersion,
      });
    } else {
      setImageSelect({
        containerImage: '',
        containerImageTag: '',
      });
    }
    console.log(tabImage);
    // reset seledted keys and table
    setImageVersions([]);
    setImageKeys([]);
    setExpandedKeysImage(['']);
  }, [tabImage]);
  useEffect(() => {
    if (models[0] && models[0].engine) {
      const arr = models[0].engine.split(':');
      let str = '';
      arr.forEach((a, i) => {
        if (i === arr.length - 1) {
          setPublicVersion(a);
        } else {
          str += i === 0 ? a :`:${a}`;
        }
      });
      setPublicName(str);
    }
  }, [models])
  return (
    // {/*  <Card> */}
    <>
      {/* 公有镜像是从模型工厂 manifest 的 engine 获取，格式为： 镜像名称：镜像版本 */}
      <Tabs defaultActiveKey='public' onChange={tab => setTabImage(tab)} value={tabImage}>
        <TabPane tab={trans('deployOnline.edgeInference.add.publicImage')} key='public'>
          {/* <Select disabled={!models.length} onChange={(value) => selectPublic(value)} value={publicSelect}> */}
          {/* <Space>
            <Select
              disabled={!models.length}
              onChange={(v:string) => selectPublicName(v)}
              style={{width:'300px'}}
              value={publicName}
            >
              { publicImages ?
                publicImages?.map(image => {
                  return <Option value={image.imageName} key={image.imageName}>{image.imageName}</Option>
                }) :
                <span>暂无公共镜像，请选择我的镜像</span>
              }
            </Select>
            <Select
              disabled={!models.length}
              onChange={v => selectPublicTag(v)}
              style={{width:'120px'}}
              // value={publicTag}
            >
              {
                imageVersions.map(v => <Option value={v} key={v}>{v}</Option>)
              }
            </Select>
          </Space> */}

          <Space>
            <Input readOnly value={publicName} style={{width:'400px'}}></Input>
            <Input readOnly value={publicVersion} style={{width:'180px'}}></Input>
          </Space>
          <div>
            { (!publicVersion.length && models.length > 0) && <span>暂无对应的公有镜像，请选择我的镜像</span> }
          </div>

        </TabPane>
        <TabPane tab={trans('deployOnline.edgeInference.add.myImage')} key='my'>
          {
            (imageSelect.containerImage && !modal && imageVersions.length) ?
            <>
              <Space>
                <Input value={imageSelect.containerImage} readOnly />
                <Select defaultValue={imageSelect.containerImageTag}>
                  {
                    imageVersions.map(v => <Option value={v} key={v}>{v}</Option>)
                  }
                </Select>
              </Space>
              <div>
                <Button type='text' icon={<PlusOutlined />} onClick={() => setModal(true)}  disabled={!models.length}>
                  更换镜像
                </Button>
              </div>
            </> :
            <section>
              <Button type='text' icon={<PlusOutlined />} onClick={() => setModal(true)}  disabled={!models.length}>
                {trans('deployOnline.edgeInference.add.addImage')}
              </Button>
              <Modal title='选择镜像' visible={modal} onOk={selectImage} onCancel={() => setModal(false)} width='800px'>
                <ATable
                  searchToolBar={searchList}
                  request={aphfRequest}
                  dataSourceAPIPath={imageAPI}
                  columns={columnsImage}
                  rowKey={record => record.imageName}
                  reloadIcon={false}
                  expandable={{
                    expandedRowKeys: expandedKeysImage,
                    onExpandedRowsChange: (expandedRows) => {expandImageChange(expandedRows)},
                    expandedRowRender: record => (
                      <ATable
                        rowSelection={{
                          type: 'radio',
                          onChange: (selectedRowKeys, selectedRows: imageVersion[]) => {
                            // setPublicSelect('');
                            setImageKeys(selectedRowKeys);
                            setImageId(record.id);
                            setImageSelect({
                              containerImage: record.imageName,
                              containerImageTag: selectedRows[0].imageVersion,
                            });
                            console.log(imageSelect);
                          },
                          selectedRowKeys: imageKeys
                        }}
                        actionRef={imageVersionRef}
                        request={aphfRequest}
                        dataSourceAPIPath={`${imageVersionAPI}${record.id}`}
                        columns={columnsImageVersion}
                        rowKey={record => record.id}
                        reloadIcon={false}
                      ></ATable>
                    )
                  }}
                ></ATable>
              </Modal>
            </section>
          }
        </TabPane>
      </Tabs>
      { !models.length && <span>请先选择模型</span> }
    </>
    // </Card>
  )
}

export default SelectImage;
